<template>
  <div class="ticket-container">
    <el-container>
      <el-header>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>取号管理</el-breadcrumb-item>
          <el-breadcrumb-item>取号列表</el-breadcrumb-item>
        </el-breadcrumb>
        <div>
          <el-button type="success" @click="editHandle">现场挂号</el-button>
        </div>
      </el-header>

      <el-container>
        <!--存放科室信息-->
        <el-aside width="200px" class="tree-wrapper">
          <el-tree :data="depList" :props="{label:'name'}" node-key="value" :highlight-current="true" @node-click="handleNodeClick"></el-tree>
        </el-aside>
        <el-main>
          <el-card class="box-card">
            <el-row>
              <el-col v-for="item in docList" @click.native="clickDoc(item)" :span="6">
                <el-card class="doctor-card">
                  <el-row :gutter="10">
                    <el-col :span="12">
                      <el-image
                          style="width: 100px; height: 100px"
                          :src="item.imageUrl"
                          fit="fit">
                      </el-image>
                    </el-col>
                    <el-col :span="12">
                      <div class="doctor-tag-wrapper">
                        <span>
                          {{item.username}}
                        </span>
                      </div>
                      <div class="doctor-tag-wrapper">
                        <span>
                          {{item.params.depname}}
                        </span>
                      </div>
                      <div class="doctor-tag-wrapper">
                        <span>
                          {{item.id}}室
                        </span>
                      </div>
                    </el-col>
                  </el-row>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog
        title="排号信息"
        :visible.sync="dialogVisible"
        width="60%"
        >
      <el-table
          :data="patientList"
          border
          style="width: 100%;margin-bottom: 20px">
        <el-table-column
            type="index"
            width="50">
        </el-table-column>
        <el-table-column
            prop="cardNo"
            label="就诊卡号"
            width="180">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名">
        </el-table-column>
        <el-table-column
            label="就诊时间">
          <template slot-scope="scope">
            {{numberToTime(scope.row.params.waitTime)}}
          </template>
        </el-table-column>
        <el-table-column
            label="状态">
          <template slot-scope="scope">
            {{convertOverTime(scope.row.params.overtime)}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                v-if="scope.row.params.overtime==null"
                size="mini"
                type="primary"
                @click="handleRegister(scope.$index, scope.row)">报到</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="现场排班"
        :visible.sync="registerVisible"
        width="50%"
        @close="registerVisible=false,orderInfo={},registerScheList=[]">
      <el-form :model="orderInfo"  ref="addFormRef" label-width="90px">
        <el-form-item label="科室" prop="depcode">
          <el-cascader
              ref="depList"
              :options="depList"
              :props="{label:'name'}"
              @change="handleChange"
              :show-all-levels="false"
              clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="排班信息">
          <el-select v-model="orderInfo.scheduleId" placeholder="请选择">
            <el-option
                v-for="item in registerScheList"
                :key="item.value"
                :label="item.params.docname+'  '+item.params.professionalTitle+'  '+item.params.workTime"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="就诊卡号" style="width: 400px">
          <el-input v-model="orderInfo.cardNo"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="registerVisible=false,orderInfo={},registerScheList=[]">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dictApi from "@/api/dict";
import patientApi from '@/api/patient'
import orderInfoApi from '@/api/orderInfo'
import scheApi from '@/api/sche'
import {dateFormat,computeTime} from "@/utils/dateUtils"
import {mapState} from "vuex";
export default {
  name: "TicketIndex",
  data() {
    return {
      url:'',
      depname:'',
      depcode:'',
      docId:'',
      cardNo:'',
      dialogVisible: false,
      registerVisible:false,
      socket:null,
      formInline: {cardNo:''},
      message:{},
      searchObj:{},
      docList:{},
      sche:{},
      orderInfo:{},
      workTimeList: [{
        value: '1',
        label: '8:30-10:30'
      }, {
        value: '2',
        label: '10:30-11:30'
      }, {
        value: '3',
        label: '14:30-15:30'
      }, {
        value: '4',
        label: '15:30-17:30'
      }],
      depList:[],
      dateList:[],
      scheList:[],
      registerScheList:[],//现场预约信息列表
      patientList:[],
    }
  },
  computed:{
    ...mapState(['user'])
  },
  beforeCreate() {

  },
  created() {
    this.init()
  },
  onMounted(){

  },
  beforeUpdate() {

  },
  destroyed() {
    this.socket.close() //离开路由之后断开websocket连接
  },
  methods:{
    init(){
      //建立websocket连接
      const userId = this.user.userId
      this.socket = new WebSocket(`ws://localhost:8080/ws/ticket/${userId}`)
      this.socket.onmessage = this.websocketonmessage;
      this.socket.onopen = this.websocketonopen;
      this.socket.onerror = this.websocketonerror;
      this.socket.onclose = this.websocketclose;
      this.getDepList()
    },
    websocketonmessage(e){
      const msg = JSON.parse(e.data)
      console.log(msg)
    },
    websocketonopen(){

    },
    websocketonerror(){

    },
    websocketclose(){

    },
    //获取所有科室
    async getDepList(){
      const{data:res} = await dictApi.findChildData(86)
      if (res.code!==200){
        return this.$message.error("查询失败")
      }
      this.depList = res.data
    },
    onSubmit(){

    },
    editHandle(){
      this.registerVisible = true
    },
    async submitForm(){
      const{data:res} = await orderInfoApi.registerOnSite(this.orderInfo)
      if (res.code!==200){
        return this.$message.error("挂号失败")
      }else {
        this.$message.success("挂号成功")
        this.registerVisible = false
        this.orderInfo = {}
        this.registerScheList=[]
      }
    },
    async handleChange(){
      const depcode = this.$refs["depList"].getCheckedNodes()[0].value;
      //构造条件，根据科室编号和今天的日期查询出所有的排班
      const searchObj = {depcode,workTime:computeTime(),workDate:new Date().toLocaleDateString()}
      const{data:res} = await scheApi.find(searchObj)
      this.registerScheList = res.data
    },
    async handleNodeClick(val,node){
      this.depname = val.name
      this.depcode = node.data.value
      this.searchObj.depcode = node.data.value
      this.searchObj.workDate = dateFormat(new Date())+''
      const {data:res} = await scheApi.findByDepcodeAndWorkDate(this.searchObj)
      this.docList = res.data
    },
    async clickDoc(item){
      const{data:res} = await patientApi.findByDocIdAndWorkDate(item.id)
      this.docId = item.id
      this.patientList = res.data
      this.dialogVisible = true
    },
    numberToTime(number){
      switch (number){
        case 1:return '8:30-10:30'
        case 2:return '10:30-11:30'
        case 3:return '14:30-15:30'
        case 4:return '15:30-17:30'
      }
    },
    //对患者进行报到
    async handleRegister(index,item){
      const{data:res} = await orderInfoApi.patientRegistration(item.params.orderInfoId)
      if (res.code!==200){
        return this.$message.error('报到失败');
      }
      const{data:resp} = await patientApi.findByDocIdAndWorkDate(this.docId)
      this.patientList = resp.data

      //向医生端发送更新患者列表请求
      const action = 'updatePatList'
      const receiverCode = this.docId
      const receiverDepcode = this.depcode
      const params = {action,receiverCode,receiverDepcode}
      this.socket.send(JSON.stringify(params))
    },
    convertOverTime(overtime){
      switch (overtime){
        case 0:return '排队中'
        case 1:return '已超时'
        case 2:return '就诊中'
        default: return '未报到'
      }
    },
  }
}
</script>

<style lang="less" scoped>
.ticket-container{
  .tree-wrapper{
    margin-top: 20px;
  }
  .box-card{
    .doctor-card{
      cursor:pointer;
      width: 250px;
      height: 150px;
      margin-bottom: 10px;
      .doctor-tag-wrapper{
        margin-bottom: 12px;
      }
    }
  }
}
</style>